import React, { useEffect, useState } from 'react';
import moment from 'moment';

import { ProTable } from '@ant-design/pro-components';

const TablePage = props => {
    const {
        requestApi,
        paginationProp = {
            page: 'pageNum',
            pageSize: 'pageSize'
        },
        getPageInfo = null,
        extraParams = {},
        extraParamsInData = {},
        formProps = {},
        ...otherProps
    } = props;

    const [scrollX, setScrollX] = useState(0);

    useEffect(() => {
        let widthTotal = 0;
        props.columns.forEach(column => {
            if (!column.hideInTable && column.width) {
                widthTotal += column.width;
            }
        });
        setScrollX(widthTotal + 100);
    }, [props.columns]);

    return (
        <ProTable
            cardBordered
            rowKey="id"
            // 禁止窗口聚焦时自动重新请求
            revalidateOnFocus={false}
            form={{
                // 禁止url带参数
                syncToUrl: false,
                ...formProps
            }}
            search={{
                labelWidth: 'auto'
            }}
            pagination={{
                showSizeChanger: true,
                defaultPageSize: 10
            }}
            dateFormatter="string"
            scroll={{
                x: scrollX
            }}
            request={async (params = {}, sort, filter) => {
                const { current, pageSize, ...others } = params;
                const sendParams = {
                    [paginationProp.pageSize]: pageSize,
                    [paginationProp.page]: current,
                    data: {
                        ...others,
                        ...extraParamsInData
                    },
                    ...extraParams
                };
                const data = await requestApi(sendParams);
                if (getPageInfo) {
                    getPageInfo(data.data.total || data.data.length);
                }
                return {
                    success: data.success,
                    // 菜单管理接口返回的data即是列表数据，且无返回数据总数，待接口优化
                    data: data.data.list || data.data ||data.data.data,
                    total: data.data.total || data.data.length
                };
            }}
            {...otherProps}
        />
    );
};

export default TablePage;
